//
//  AppController.m
//  RenamePix
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "AppController.h"

@implementation AppController

- (id)init;
{
	if(![super init])
		return self;
	files = [[NSMutableArray alloc] init];
	fileTypes = [[NSArray arrayWithObjects:@"jpg", @"jpeg", @"tif", @"tiff", @"gif", @"bmp", @"png", nil] retain];
	[NSApp setDelegate:self];
	return self;
}

- (void)awakeFromNib
{
	[mainImageView setAppController:self];
}

- (void)dealloc
{
	[files release];
	[super dealloc];
}

- (void)openFiles:(NSArray *)filenames inDirectory:(NSString *)directory;
{
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *file, *path;
	BOOL dir;
	for(file in filenames)
	{
		path = (directory == nil) ? file : [NSString stringWithFormat:@"%@/%@", directory, file];
		if(![manager fileExistsAtPath:path isDirectory:&dir])
			continue;
		if(!dir && ![file isEqualToString:@".DS_Store"] && [fileTypes containsObject:[file pathExtension]])
		{
			[files addObject:[NSURL fileURLWithPath:path]];
		}
		else
		{
			NSArray *contents = [manager directoryContentsAtPath:path];
			[self openFiles:contents inDirectory:path];
		}
	}
}

- (void)openFiles:(NSArray *)filenames;
{
	[files removeAllObjects];
	[self openFiles:filenames inDirectory:nil];
	[self showImage:0];
}

- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames;
{
	[self openFiles:filenames];
}

- (void)filePanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	[self openFiles:[sheet filenames]];
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}

- (void)openDocument:(id)sender;
{
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	[panel setAllowsMultipleSelection:YES];
	[panel setCanChooseDirectories:YES];
	[panel beginSheetForDirectory:NSHomeDirectory() 
		file:nil 
		types:fileTypes 
		modalForWindow:mainWindow 
		modalDelegate:self 
		didEndSelector:@selector(filePanelDidEnd:returnCode:contextInfo:) 
		contextInfo:nil];
}

- (void)setFiles:(NSArray *)newArray
{
	[files setArray:newArray];
}

- (void)showImage:(int)index;
{
	if(index >= [files count])
		return;
	currentIndex = index;
	[mainWindow makeKeyAndOrderFront:self];
	
	[leftArrow setEnabled:(currentIndex != 0)];
	[rightArrow setEnabled:(currentIndex != ([files count] - 1))];
	
	NSURL *filepath = [files objectAtIndex:index];
	[mainImageView setImagePath:filepath];
	[imagePropertyView setStringValue:[mainImageView imageDescription]];
	
	NSString *filename = [[filepath path] lastPathComponent];
	NSUInteger lastPeriod = [filename rangeOfString:@"." options:NSBackwardsSearch].location;
	[imageNameField setStringValue:[filename substringToIndex:lastPeriod]];
	[imageNameField selectText:self];
	
	[mainWindow setTitle:[NSString stringWithFormat:@"%@ (%d/%d)", [filepath path], (index + 1), [files count]]];
}

- (IBAction)leftArrowPressed:(id)sender;
{
	[self showImage:currentIndex - 1];
}

- (IBAction)rightArrowPressed:(id)sender;
{
	[self showImage:currentIndex + 1];
}

- (IBAction)closeErrorWindow:(id)sender;
{
	[NSApp stopModalWithCode:0];
}

- (IBAction)doRename:(id)sender;
{
	NSLog(@"Do rename?");
	NSString *oldPath = [[files objectAtIndex:currentIndex] path];
	NSMutableArray *components = [NSMutableArray arrayWithArray:[oldPath pathComponents]];
	NSString *oldName = [components lastObject];
	NSString *newName = [NSString stringWithFormat:@"%@.%@", [imageNameField stringValue], [oldName pathExtension]];
	[components replaceObjectAtIndex:([components count] - 1) withObject:newName];
	
	NSFileManager *manager = [NSFileManager defaultManager];
	NSString *newPath = [NSString pathWithComponents:components];
	
	if([manager fileExistsAtPath:newPath])
	{
		[errorLabel setStringValue:@"File exists at path"];
		[NSApp beginSheet:errorWindow modalForWindow:mainWindow modalDelegate:nil didEndSelector:nil contextInfo:nil];
		[NSApp runModalForWindow:errorWindow];
		
		[NSApp endSheet:errorWindow];
		[errorWindow orderOut:nil];
		return;
	}
	[manager movePath:oldPath toPath:newPath handler:nil];
	[mainWindow setTitle:[NSString stringWithFormat:@"%@ (%d/%d)", newName, (currentIndex + 1), [files count]]];
	[files replaceObjectAtIndex:currentIndex withObject:newPath];
	
	if((currentIndex + 1) < [files count])
	{
		[self showImage:currentIndex + 1];
	}
}

@end
